package com.operamasksui;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

@Controller
@RequestMapping("/user")
public class UserController {

    protected final Log logger = LogFactory.getLog(getClass());
    
    private UserServices userServices = new UserServicesImpl();
    
    @RequestMapping(value = "/search", method = RequestMethod.POST)
	@ResponseBody
    public ModelAndView findAllUser(HttpServletRequest request, HttpServletResponse response)
    {
    	GridDataModel<User> model = new GridDataModel<User>();
    	String startStr = request.getParameter("start");
	    String limitStr = request.getParameter("limit");
	    
	    int start = Integer.parseInt(StringUtils.isNotBlank(startStr)?startStr:"0");
	    int limit = Integer.parseInt(StringUtils.isNotBlank(limitStr)?limitStr:"15");
	    List<User> users = userServices.findAllUser();
	    int end = start + limit;
	    int total = users.size();
        end = end > total ? total : end;
        if(start <= end) {
        	model = packegUserToGridModel(users , start , end);
        	String userJSON = JSONObject.fromObject(model).toString();
        	writerToClient(response , userJSON);
        }
        return null;
    }
    
    @RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
    public ModelAndView login(HttpServletRequest request, HttpServletResponse response) throws IOException
    {
    	System.err.println("登录了");
    	response.sendRedirect("../index.html");
    	return null;
    	//return new ModelAndView(new RedirectView("redirect:index.html")); 
    }
    
    public ModelAndView delete(HttpServletRequest request, HttpServletResponse response)
    {
    	String userId = request.getParameter("id");
		if(StringUtils.isNotBlank(userId))
		userServices.delete(userServices.findUserById(Integer.valueOf(userId)));
		writerToClient(response,"1");
    	return null;
    }
    
    public ModelAndView save(HttpServletRequest request, HttpServletResponse response)
    {
    	User user = null;
    	String id = request.getParameter("Uid");
    	String address = request.getParameter("address");
    	String age = request.getParameter("age");
    	String email = request.getParameter("email");
    	String tel = request.getParameter("tel");
    	String userName = request.getParameter("userName");
		if(StringUtils.isNotBlank(id)){ //修改
			user = userServices.findUserById(Integer.valueOf(id));
		}else{//新增
			user = new User();
		}
		user.setAddress(address);
		user.setAge(age != null?Integer.valueOf(age):0);
		user.setEmail(email);
		user.setTel(tel);
		user.setUserName(userName);
		userServices.saveOrUpdate(user);
		writerToClient(response , "1");
		
		return null;
    }
    
    private GridDataModel<User> packegUserToGridModel(List<User> users , int start , int end)
	{
		if(users != null && users.size() > 0){
			GridDataModel<User> userModel = new GridDataModel<User>();
			userModel.setTotal(users.size());
		    userModel.setRows(users.subList(start, end));
		    return userModel;
		}else{
			return null;
		}
	}
    
    private void writerToClient(HttpServletResponse response , String resStr)
	{
		response.setCharacterEncoding("UTF-8");
		PrintWriter writer = null;
		 try {
			 writer = response.getWriter();
			 writer.write(resStr);
			 writer.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}